//
//  ShopViewController.m
//  欢乐美食
//
//  Created by 遇水 on 15/5/27.
//  Copyright (c) 2015年 遇水. All rights reserved.
//  上边有一个

#import "SearchViewController.h"
#import "UIBarButtonItem+Extension.h"
#import "UIImageView+WebCache.h"
#import "MSDeals.h"
#import "SingerDealController.h"

#import "ZYQSphereView.h"

#import "StoreViewCell.h"
#import "MSFoots.h"
#import "MSMetaDataTool.h"

#import "historyTool.h"
@interface SearchViewController ()<UISearchBarDelegate , UITableViewDelegate, UITableViewDataSource>
{
    UISearchBar *_search;
    UIBarButtonItem *_liftButton;
    CGSize _kbSize;
    
    //添加标签云
    ZYQSphereView *_splereView;
    NSTimer *_timer;
}

@property (nonatomic, strong) UITableView    *tableView;

@property (nonatomic, strong) NSArray    *dataSource;

@property (nonatomic, strong) UIActivityIndicatorView    *activityView;
@end

@implementation SearchViewController
-(NSArray *)dataSource{
    if (_dataSource==nil) {
        _dataSource = [NSArray array ];
        //实现具体的加载实现
    }
    return _dataSource;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initSearchBar];
    [self initTableView];
    [self initSphereView];   //初始化这个控件
}

#pragma mark - 初始化操作
/**
 *  添加中间的搜索框
 */
-(void)initSearchBar{
    UISearchBar *search = [[UISearchBar alloc]initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), 40)];
    search.delegate = self;
    NSString *cityStr = [[NSUserDefaults standardUserDefaults]stringForKey:@"city"];
    NSString *placeholder = [cityStr stringByAppendingString:@"、美食"];
    search.placeholder =placeholder;
    self.navigationItem.titleView = search;
    _search  = search;
    
}
/**
 *  添加搜索结果显示tableView
 */
-(void)initTableView{
    UITableView *tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), CGRectGetHeight(self.view.bounds)) style:UITableViewStylePlain];
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    tableView.hidden = YES;
    [self.view addSubview: tableView];
    self.tableView= tableView;
}
///初始化标签云
-(void)initSphereView
{

    _splereView = [[ZYQSphereView alloc]initWithFrame:CGRectMake(10, 100, self.view.width - 20, self.view.width - 20)];
    _splereView.center = CGPointMake(self.view.width / 2, self.view.height / 2);
    
    //获得子控件的内容
    MSFoots *foots = [MSMetaDataTool sharedMetaDataTool].foots[0];
    NSArray *subFoot = foots.subcategories;
    //创建子控件
    NSMutableArray *views = [[NSMutableArray alloc]init];
    for (int i = 0; i< subFoot.count; i++ ) {
        UIButton *subV = [[UIButton alloc]init];
        //根据其中的内容获得size大小
        NSString *text = subFoot[i];
        CGSize size = [text sizeWithFont:subV.font];
        subV.frame = CGRectMake(0, 0, size.width, size.height);
        [subV setTitle:[NSString stringWithFormat:@"%@",subFoot[i]]forState:UIControlStateNormal];
        subV.backgroundColor = [UIColor colorWithRed:arc4random_uniform(100)/100. green:arc4random_uniform(100)/100. blue:arc4random_uniform(100)/100. alpha:1];

        subV.layer.masksToBounds = YES;
        subV.layer.cornerRadius = 3;
        [subV addTarget:self action:@selector(subClick:) forControlEvents:UIControlEventTouchUpInside];
        [views addObject:subV];
    }
    [_splereView setItems:views];
    
    _splereView.isPanTimerStart = YES;
    
    [self.view addSubview:_splereView];
    [_splereView timerStart];
    
}


//标签云子控件的事件
-(void)subClick:(UIButton *)button
{
    //获得按钮的内容
    BOOL isStart=[_splereView isTimerStart];
    
    [_splereView timerStop];
    
    [UIView animateWithDuration:0.3 animations:^{
        button.transform=CGAffineTransformMakeScale(1.5, 1.5);
    } completion:^(BOOL finished) {
        [UIView animateWithDuration:0.2 animations:^{
            button.transform=CGAffineTransformMakeScale(1, 1);
            if (isStart) {
                [_splereView timerStart];
            }
        }];
    }];
    UIActivityIndicatorView *activityView  = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    self.activityView = activityView;
    [activityView startAnimating];
    [self.view addSubview:activityView];
    [self laodDeal:button.titleLabel.text];
    

}

#pragma mark 请求数据
-(void)laodDeal:(NSString *)keyword{

    _splereView.hidden = YES;
MSFindDealsParam *param = [[MSFindDealsParam alloc]init];
param.city = [[NSUserDefaults standardUserDefaults]stringForKey:@"city"];
    param.keyword = keyword;
[MSDealTool findDeals:param success:^(MSFindDealsResult *result) {
    self.dataSource = result.deals;
    if (result.deals.count == 0) {
        //说明没有数据
        [MBProgressHUD showError:@"请求结果为空，请重新输入其他关键字"];
        _splereView.hidden = NO;
    }
    [self.activityView stopAnimating];
    self.tableView.hidden = NO;
    
    [self.tableView reloadData];
    
} failure:^(NSError *error) {
    
    [MBProgressHUD showError:@"加载失败，内容不正确或者网络加载失败"];

    
    _splereView.hidden = NO;
    
}];

}


#pragma mark - searchBarDelegate
/** 搜索框中的内容改变*/
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
    
}
-(BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar{
    [_search setShowsCancelButton:YES animated:YES];
    NSLog(@"点击搜索框");
    _splereView.hidden = YES;
    return YES;
}
/**
 *  隐藏键盘
 *
 */
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [_search endEditing:YES];
#warning 将搜索栏中的文字显示为空，并且提示为用户以前选择的
    _splereView.hidden = NO;
    [_search setShowsCancelButton:NO animated:YES];     //设置cancel按钮为不显示

}

/** 搜索框点击取消按钮*/
-(void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{
    [_search resignFirstResponder]; //取消第一响应者
    _splereView.hidden = NO;
    if (!self.tableView.hidden) {
        self.tableView.hidden = YES;
    }
    [_search setShowsCancelButton:NO animated:YES];
    
}

/**点击搜索按钮时候触发*/
-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
   NSString *text =  _search.text;
    NSLog(@"点击搜索了");
    [self laodDeal:text];
    [self.view endEditing:YES];

}


#pragma mark - tableviewDelegate
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    StoreViewCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
    return cell.height;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return  self.dataSource.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *ID = @"cell";
    StoreViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if (cell ==nil) {
        cell =  [[[NSBundle mainBundle]loadNibNamed:@"StoreViewCell" owner:nil options:nil]firstObject];
    }
    cell.deal  =  self.dataSource[indexPath.item];


    return  cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    //选中时的内容
    SingerDealController *singerDeal = [[SingerDealController alloc]init];
    singerDeal.deal = self.dataSource[indexPath.item];
    //清除所有的数据
    
    [[historyTool sharedhistoryTool] saveHistoryDeal:self.dataSource[indexPath.item]];
    
    self.dataSource = nil;
    [self.navigationController pushViewController:singerDeal animated:YES];
    
}
@end
